
import store from '@/store/index'

export function checkPermission(url) {
  const permissions = store.state.user.accessPermissions
  if (permissions instanceof Set) {
    return permissions.has(computedUrlPermissions(url))
  } else {
    return false
  }
}

export function computedUrlPermissions(url) {
  // 判断url是不是以
  let returnUrl = ''
  url = url.replace(/^\//g, '')
  const urlArr = url.split('/')
  if (urlArr.length > 1) {
    const lastOne = urlArr.splice(urlArr.length - 1, 1)
    let baseUrl
    if (urlArr.length > 1) {
      baseUrl = urlArr.join('_')
    } else {
      baseUrl = urlArr[0]
    }
    returnUrl = baseUrl + '_' + lastOne[0]
  } else {
    returnUrl = urlArr[0]
  }
  return returnUrl
}

// 表单验证规则计算
export function computedRules(form) {
  let str
  const rules = {}
  for (str in form) {
    rules[str] = form[str].rules
    if (form[str].required) {
      if (!(rules[str] instanceof Array)) rules[str] = []
      rules[str].push({ required: true, message: '请输入 ' + form[str].placeholder, trigger: 'blur' })
    }
  }
  return rules
}

export function computeForm(baseForm) {
  baseForm = JSON.parse(JSON.stringify(baseForm))
  const obj = {}
  let attr
  for (attr in baseForm) {
    obj[attr] = baseForm[attr].value
  }
  return obj
}
